
load("Brexit_Rep.RData")

leavers.sub <- brexit.sub2[which(brexit.sub2$leaver == 1),]
remainers.sub <- brexit.sub2[which(brexit.sub2$leaver == 0),]

leavers.sub <- as.data.frame(leavers.sub)
remainers.sub <- as.data.frame(remainers.sub)

all.mediators.6 <- Cs(farage.6,efficacy.vote.6,gov.trust.6, 
                      bad.past.econ.6,hh.bad.past.econ.6) 
all.mediators.5 <- Cs(farage.5,efficacy.vote.5,gov.trust.5, 
                      bad.past.econ.5,hh.bad.past.econ.5)  

dvs <- Cs(migs.take.jobs.6,migs.more.terror.6,closed.immigrants.6,hurt.standing.refugee.6,
          threaten.culture.refugee.6,overwhelm.welfare.refugee.6)

m.all.jobs <- vector(length(all.mediators.6), mode = "list")
names(m.all.jobs) <- all.mediators.6

m.all.terror <- vector(length(all.mediators.6), mode = "list")
names(m.all.terror) <- all.mediators.6

m.all.closed <- vector(length(all.mediators.6), mode = "list")
names(m.all.closed) <- all.mediators.6

m.all.standing <- vector(length(all.mediators.6), mode = "list")
names(m.all.standing) <- all.mediators.6

m.all.cult <- vector(length(all.mediators.6), mode = "list")
names(m.all.cult) <- all.mediators.6

m.all.welf <- vector(length(all.mediators.6), mode = "list")
names(m.all.welf) <- all.mediators.6


m.all <- list(m.all.jobs,m.all.terror,m.all.closed, m.all.standing,m.all.cult,m.all.welf)

names(m.all) <- dvs

m.all.leavers <- m.all
m.all.remainers <- m.all

#install.packages("mediation")
require(mediation)


indices <- 1:length(all.mediators.6)

for (j in 1:(length(dvs))){
  
  for (i in 1:(length(all.mediators.6))){
    
    indices2 <- indices[-i] # for alternative mediators, must remove the main mediator
    
    
    m.all.leavers[[dvs[j]]][[all.mediators.6[i]]] <- 
      multimed(outcome = dvs[j], med.main = all.mediators.6[i], 
               med.alt = all.mediators.6[indices2],
               treat = "post", covariates = all.mediators.5, data = leavers.sub, sims = 1000, 
                                                                           weight = "w8w6")
    
  }
}



for (j in 1:(length(dvs))){
  
  for (i in 1:(length(all.mediators.6))){
    
    indices2 <- indices[-i] # for alternative mediators, must remove the main mediator
    
    print(indices2)
    
    m.all.remainers[[dvs[j]]][[all.mediators.6[i]]] <- multimed(outcome = dvs[j], med.main = all.mediators.6[i], med.alt = all.mediators.6[indices2],
                                                                             treat = "post", covariates = all.mediators.5, data = remainers.sub, sims = 1000,
                                                                             weight = "w8w6")
    
    
  }
}


